async function captureFullPage() {
  try {
    // 保存原始滚动位置
    const originalScrollPos = window.scrollY;
    const originalScrollBehavior = document.documentElement.style.scrollBehavior;
    document.documentElement.style.scrollBehavior = 'auto';

    // 获取页面完整尺寸
    const fullHeight = Math.max(
      document.documentElement.scrollHeight,
      document.body.scrollHeight
    );
    const fullWidth = Math.max(
      document.documentElement.scrollWidth,
      document.body.scrollWidth
    );
    const viewportHeight = window.innerHeight;

    // 创建canvas
    const canvas = document.createElement('canvas');
    const context = canvas.getContext('2d');
    const devicePixelRatio = window.devicePixelRatio || 1;

    // 设置canvas尺寸
    canvas.width = fullWidth * devicePixelRatio;
    canvas.height = fullHeight * devicePixelRatio;

    // 分段截图并拼接
    for (let currentPos = 0; currentPos < fullHeight; currentPos += viewportHeight) {
      // 滚动到指定位置
      window.scrollTo(0, currentPos);

      // 等待页面重绘和动画完成
      await new Promise(resolve => setTimeout(resolve, 150));

      // 获取当前视图截图
      const dataUrl = await new Promise((resolve, reject) => {
        chrome.runtime.sendMessage({type: 'captureVisible'}, response => {
          if (chrome.runtime.lastError) {
            reject(chrome.runtime.lastError);
          } else if (!response || !response.dataUrl) {
            reject(new Error('截图失败'));
          } else {
            resolve(response.dataUrl);
          }
        });
      });

      // 将截图绘制到canvas
      const img = await new Promise((resolve, reject) => {
        const image = new Image();
        image.onload = () => resolve(image);
        image.onerror = () => reject(new Error('图片加载失败'));
        image.src = dataUrl;
      });

      context.drawImage(
        img,
        0,
        currentPos * devicePixelRatio,
        fullWidth * devicePixelRatio,
        viewportHeight * devicePixelRatio
      );
    }

    // 恢复原始滚动位置和行为
    window.scrollTo(0, originalScrollPos);
    document.documentElement.style.scrollBehavior = originalScrollBehavior;

    // 转换为图片数据
    return canvas.toDataURL('image/png');
  } catch (error) {
    console.error('截图过程出错:', error);
    throw error;
  }
}

// 监听来自popup的消息
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  if (request.action === 'capture') {
    captureFullPage()
      .then(imageData => {
        sendResponse({imageData});
      })
      .catch(error => {
        console.error('Capture error:', error);
        sendResponse({error: error.message});
      });
    return true; // 表示将异步发送响应
  }
});

// 通知popup脚本已加载
chrome.runtime.sendMessage({type: 'contentScriptReady'});

